package org.study.bookmanager.controller;


import jakarta.annotation.Resource;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.study.bookmanager.io.reponse.RestBean;
import org.study.bookmanager.io.request.Borrow.AddBorrowReq;
import org.study.bookmanager.io.request.PageReq;
import org.study.bookmanager.service.BorrowService;

import java.util.Date;

@RestController
@RequestMapping(value = "/v1/borrow" ,produces = "application/json;charset=UTF-8")
public class BorrowController {
    @Resource
    private BorrowService borrowService;

    @PostMapping("/")
    String addBorrow(@RequestBody AddBorrowReq req){
        if(req.getDue_date()==null){
            return RestBean.handlerError(RestBean.Code.请填写预期归还时间);
        }
        if(req.getDue_date().before(new Date())){
            return RestBean.handlerError(RestBean.Code.预期归还时间不能早于现在);
        }
        UserDetails details = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Object resp=borrowService.addBorrow(details,req);
        if(RestBean.handlerError(resp)!=null){
            return RestBean.handlerError(resp);
        }
        return RestBean.success(resp);
    }

    @PutMapping("/{Id}/return")
    String returnBorrow(@PathVariable int Id){
        Object resp=borrowService.returnBorrow(Id);
        if(RestBean.handlerError(resp)!=null){
            return RestBean.handlerError(resp);
        }
        return RestBean.success(resp);
    }

    @PostMapping("/list")
    String getBorrows(@RequestBody PageReq pageReq){
        UserDetails details = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Object resp=borrowService.getBorrows(details,pageReq);
        if(RestBean.handlerError(resp)!=null){
            return RestBean.handlerError(resp);
        }
        return RestBean.success(resp);
    }

    @GetMapping("/{Id}")
    String getBorrow(@PathVariable int Id){
        Object resp=borrowService.getBorrow(Id);
        if(RestBean.handlerError(resp)!=null){
            return RestBean.handlerError(resp);
        }
        return RestBean.success(resp);
    }

    @PutMapping("/{Id}")
    String updateBorrow(@PathVariable int Id){
        Object resp=borrowService.updateBorrow(Id);
        if(RestBean.handlerError(resp)!=null){
            return RestBean.handlerError(resp);
        }
        return RestBean.success(resp);
    }
}
